#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <stdlib.h>
#include <assert.h>

static char *wday_print(const struct tm *t)
{
	char *temp;
	temp = (char *)malloc(sizeof(temp) * 100);
	assert(temp);

	switch(t->tm_wday + 1)
	{
		case 1 : return temp = "星期日";
		case 2 : return temp = "星期一";
		case 3 : return temp = "星期二";
		case 4 : return temp = "星期三";
		case 5 : return temp = "星期四";
		case 6 : return temp = "星期五";
		case 7 : return temp = "星期六";
	}
}

void time_print(const struct tm *t)
{

	printf("\n\n%d 年 %d 月 %d 日 %s %d:%d:%d\n\n\n",
			t->tm_year + 1900,
			t->tm_mon + 1,
			t->tm_mday,
			wday_print(t),
			t->tm_hour,
			t->tm_min,
			t->tm_sec);
}

int main(void)
{
	time_t now;
	printf("Calender Time : %ld\n", time(&now));//time_t time(time_t *t)获取日历时间
	
	struct tm *p_utc = NULL;
	p_utc = gmtime(&now);//struct tm *gmtime(const time_t *t)将日历时间转化为UTC时间，保存到struct tm结构体中
	if(p_utc != NULL)
	{
		printf("calTime to UTC : %d - %d - %d\n", 
				p_utc->tm_hour,
				p_utc->tm_min,
				p_utc->tm_sec);
	}

	struct tm *p_local = NULL;
	p_local = localtime(&now);//struct tm *localtime(const time_t* t)将日历时间转化为本地时间，保存到struct tm结构体中
	if(p_local != NULL)
	{
		printf("calTime to locTime : %d - %d - %d\n",
				p_local->tm_hour,
				p_local->tm_min,
				p_local->tm_sec);
	}

	time_print(p_local);

	printf("ASCII time : %s", asctime(p_local));//char *asctime(const struct tm *t)将struct tm格式的时间转化为字符串

	printf("calTime to locTime 2 : %s", ctime(&now));//char *ctime(const time_t *t)将日历时间转化为本地时间字符串

	struct timeval t_val;
	gettimeofday(&t_val, NULL);//int gettimeofday(struct timeval *tv, struct timezone *tz)获取从今日凌晨到现在的时间差，struct timeval结构体指针用于存储时间值
	printf("Gettimeofday : time_t : %ld suseconds_t : %ld\n",
			t_val.tv_sec,
			t_val.tv_usec);

	printf("mktime : %ld\n", mktime(p_local));//time_t mktime(struct tm *t)将struct tm结构体的时间转化为日历时间

	printf("sleep time : %d\n", sleep(3));//unsigned int sleep(unsigned int seconds)使用程序睡眠seconds秒

	printf("usleep time : %d\n", usleep(1000));//void usleep(unsigned long usec)使用程序睡眠usec微秒

}
